<!--
Version 0.1
SEMF - Web Desiging Framework for Sport Event Managment
Copyright (C) 2006, SEMF Developers

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>CRUD Plugin</title>
<script language="javascript" src="../../yui/yahoo.js"></script>
<script language="javascript" src="../../yui/event.js"></script>
<script language="javascript" src="../../yui/treeview.js"></script>


<link href="../../styles/tree.css" rel="stylesheet" type="text/css" />
</head>

<body>

<?php
$root_project_home=$_GET['project_home'];
$semf_root = "../../";

$current_module_name = $_GET['moduleName'];
$current_table_name = $_GET['tableName'];

$op_name = $_GET['op_name'];
$op_act = $_GET['op_act'];

$plugin_param = $_GET['pluginParam'];
$container_id = $_GET['containerId'];

if($plugin_param) //then everything is in there..
{
	$pos = strpos($plugin_param, '___');
	$root_project_home = substr($plugin_param,0, $pos);
	
	$rest = substr($plugin_param, $pos +3);
	$pos = strpos($rest, '___');
	$current_module_name = substr($rest, 0, $pos);
	$current_table_name = substr($rest, $pos+3);
}


$project_home = $semf_root.$root_project_home;


$current_module_tables = array();

$files = array();
$d = dir($project_home);
// Loop through all of the files:
$i = 0;
while (false !== ($file = $d->read()))
{
	// If the file is not this file, and does not start with a '.' or '~'
	// and does not end in LCK, then store it for later display:
	if ( ($file{0} != '.') &&
		 ($file{0} != '~') &&
		 (substr($file, -3) != 'php') &&
		 is_dir($project_home.$file) )
	{
		if($file == "store")
		{
			continue;
		}
		$files[$i++] = $file;
	}
}


$modules = array();
$tables = array();

foreach($files as $file)
{
	$module_name = $file;
	$modules[count($modules)] = $module_name;
	
	if($current_module_name != $module_name)
	{
		continue;
	}

	$module_xml = $project_home.$file."/"."module.xml";
	
	$doc = new DOMDocument();
	$doc->load($module_xml);
	
	if($doc == NULL || $doc->documentElement == NULL)
	{
		exit();
	}
	$table_elements = $doc->documentElement->childNodes;
	
	
	foreach ($table_elements as $table_element)
	{
		if($table_element->nodeType != XML_ELEMENT_NODE)
		{
			continue;
		}
		$is_interface = $table_element->getAttribute("interface");
		if($is_interface == "yes")
		{
			continue;
		}
		$table_name = $table_element->getAttribute("name");
		$tables[count($tables)] = $table_name;
		
		$current_module_tables[$table_name] = 1;
	}
	if($current_table_name == "" && count($tables) >0)
	{
		$current_table_name = $tables[0];
	}
}

if($current_module_tables[$current_table_name] != 1)
{
	//the table is not a table from the module..
	$current_table_name = $tables[0];
}

$cond_dir = "";
$current_conf_file = "";

$doc = NULL;
$conf_dir = "";
if(isset($current_module_name) && isset($current_table_name) && 
	$current_module_name != "" && $current_table_name != "")
{
	if(!is_dir($project_home."/store"))
	{
		mkdir($project_home."/store");
	}
	if(!is_dir($project_home."/store/other"))
	{
		mkdir($project_home."/store/other");
	}
	if(!is_dir($project_home."/store/other/plug_ins"))
	{
		mkdir($project_home."/store/other/plug_ins");
	}
	if(!is_dir($project_home."/store/other/plug_ins/CRUD/"))
	{
		mkdir($project_home."/store/other/plug_ins/CRUD/");
	}
	$conf_dir = $project_home."/store/other/plug_ins/CRUD/";
	$file_name = $conf_dir.$current_module_name."_".$current_table_name.".xml";
	
	if(file_exists($file_name))
	{
		$doc = new DOMDocument();
		$doc->load($file_name);
	}
	else
	{
		copy("CRUD.dtd", $conf_dir."CRUD.dtd");
		$impl = new DomImplementation;
		$dtd = $impl->createDocumentType("CRUD", "", "CRUD.dtd");
		$doc = $impl->createDocument("", "", $dtd);
		// Set other properties
		$doc->encoding = "UTF-8";
		$doc->standalone = "no";
		$root_ele = $doc->createElement("CRUD");
		$root_ele-> setAttribute("table_module", $current_module_name);
		$root_ele-> setAttribute("table", $current_table_name);
		$root_ele-> setAttribute("op", "new");
		$doc->appendChild($root_ele);
		
		$fields = return_fields($project_home,
					$current_module_name,
					$current_table_name);
		$i = 0;
		foreach($fields as $field)
		{
			$field_element = $doc->createElement("field");
			$root_ele->appendChild($field_element);
			
			$field_element->setAttribute("id", "base__".$i);
			$field_element->setAttribute("name", $field["name"]);
			$field_element->setAttribute("type", $field["type"]);
			$field_element->setAttribute("op", "open");
			if($field["isarray"] == "yes")
			{
				$field_element->setAttribute("isarray", "yes");
			}
			if($field["istable"] == 1)
			{
				$pos = strpos($field["table"], ".");
				$table_module = substr($field["table"], 0, $pos);
				$table_name = substr($field["table"], $pos+1);
				
				$field_element->setAttribute("table", $table_name);
				$field_element->setAttribute("table_module", $table_module);
				
				//this is also needed some time..
				$child_fields = return_fields($project_home,
					$table_module,
					$table_name);
					
				$j = 0;
				foreach($child_fields as $child_field)
				{
					$child_field_element = $doc->createElement("field");
					$field_element->appendChild($child_field_element);
					
					$child_field_element->setAttribute("id", "base__".$i."__".$j);
					$j ++;
					$child_field_element->setAttribute("name", $child_field["name"]);
					$child_field_element->setAttribute("type", $child_field["type"]);
					$child_field_element->setAttribute("op", "open");
					if($child_field["isarray"] == "yes")
					{
						$child_field_element->setAttribute("isarray", "yes");
					}
					if($child_field["istable"] == 1)
					{
						$pos = strpos($child_field["table"], ".");
						$table_module = substr($child_field["table"], 0, $pos);
						$table_name = substr($child_field["table"], $pos+1);
						
						$child_field_element->setAttribute("table", $table_name);
						$child_field_element->setAttribute("table_module", $table_module);					
						
					}
				}
			}
			$i ++;
		}
		$doc->save($file_name);
	}
	
	$root_element = $doc->documentElement;
	if(isset($container_id))
	{
		$root_element->setAttribute("target", $container_id);
		$doc->save($file_name);
	}
	else
	{
		$container_id = $root_element->getAttribute("target");
	}
	if(isset($op_name) && isset($op_act))
	{
		$doc->validate();
		//get into the modulename someway..
		$element_id = $op_name;
		$element = $doc->getElementById($element_id);
		if($op_act == "new")
		{
			$element->setAttribute("op", "new");
		}
		if($op_act == "new")
		{
			
			// and then add all the child of the table..
			$module_name = $element->getAttribute("table_module");
			$table_name = $element->getAttribute("table");
			
			//set all fields..

			$module_xml = $project_home.$module_name."/"."module.xml";
			
			$module_doc = new DOMDocument();
			$module_doc->load($module_xml);
			
			if($module_doc == NULL || $module_doc->documentElement == NULL)
			{
				echo "Module XML: ".$module_xml." doesnt exists\n";
				exit();
			}
			$table_elements = $module_doc->documentElement->childNodes;
			
			
			foreach ($table_elements as $table_element)
			{
				if($table_element->nodeType != XML_ELEMENT_NODE)
				{
					continue;
				}
				$is_interface = $table_element->getAttribute("interface");
				if($is_interface == "yes")
				{
					continue;
				}
				$module_table_name = $table_element->getAttribute("name");
				if($module_table_name != $table_name)
				{
					continue;
				}
				$fields = return_fields($project_home,
					$module_name,
					$table_name);
				$i = 0;
				foreach($fields as $field)
				{
					//find the field_element
					$field_element = $doc->getElementById($element_id."__".$i);
					
					if($field_element == NULL)
					{
						$field_element = $doc->createElement("field");
						$element->appendChild($field_element);
						
						$field_element->setAttribute("id", $element_id."__".$i);
						$field_element->setAttribute("name", $field["name"]);
						$field_element->setAttribute("type", $field["type"]);
						$field_element->setAttribute("op", "open");
						if($field["isarray"] == "yes")
						{
							$field_element->setAttribute("isarray", "yes");
						}
					}
					if($field["istable"] == 1)
					{
						$pos = strpos($field["table"], ".");
						$table_module = substr($field["table"], 0, $pos);
						$field_table_name = substr($field["table"], $pos+1);
						
						$field_element->setAttribute("table", $field_table_name);
						$field_element->setAttribute("table_module", $table_module);
						
						$child_fields = return_fields($project_home,
							$table_module,
							$field_table_name);
						
						$j = 0;
						foreach($child_fields as $child_field)
						{
							//if the element exist jsut exist..
							$child_field_element = $doc->getElementById($element_id."__".$i."__".$j);
							if($child_field_element != NULL)
							{
								continue;
							}
							$child_field_element = $doc->createElement("field");
							$field_element->appendChild($child_field_element);
							
							$child_field_element->setAttribute("id", $element_id."__".$i."__".$j);
							$j ++;
							$child_field_element->setAttribute("name", $child_field["name"]);
							$child_field_element->setAttribute("type", $child_field["type"]);
							$child_field_element->setAttribute("op", "open");
							if($child_field["isarray"] == "yes")
							{
								$child_field_element->setAttribute("isarray", "yes");
							}
							if($child_field["istable"] == 1)
							{
								$pos = strpos($child_field["table"], ".");
								$table_module = substr($child_field["table"], 0, $pos);
								$field_table_name = substr($child_field["table"], $pos+1);
								
								$child_field_element->setAttribute("table", $field_table_name);
								$child_field_element->setAttribute("table_module", $table_module);					
								
							}
						}
					}//this is also needed some time..
					
					$i ++;
				}
				$doc->save($file_name);
			}
		}
		elseif($op_act == "open")
		{
			//just remove all the childs..
			$element->setAttribute("op", "open");
			$child = $element->firstChild;
			/*echo count($element->childNodes);
			echo $element->getAttribute("id");
			echo $child; */
			/*while($child != NULL)
			{
				$element->removeChild($child);
				$child = $element->firstChild;
			}*/
			//we are done.;)
			$doc->save($file_name);
		}
	}
}

function return_fields($project_home,
					$current_module_name,
					$current_table_name)
{
	$module_xml = $project_home.$current_module_name."/"."module.xml";
	

	$doc2 = new DOMDocument();
	$doc2->load($module_xml);
	
	$table_elements = $doc2->documentElement->childNodes;
	
	$all_fields = array();
	
	foreach ($table_elements as $table_element)
	{
		if($table_element->nodeType != XML_ELEMENT_NODE)
		{
			continue;
		}
		$is_interface = $table_element->getAttribute("interface");
		if($is_interface == "yes")
		{
			continue;
		}
		$table_name = $table_element->getAttribute("name");
		if($table_name != $current_table_name)
		{
			continue;
		}
		
		$all_fields = array();
		
		$direct_fields = array();
		
		$field_elements = $table_element->childNodes;
		
		foreach($field_elements as $field_element)
		{		
			if($field_element->tagName != "field")
			{
				continue;
			}
			$name = $field_element->getAttribute("name");
			$direct_fields[$name] = 1;
			$field_info = array(
					"name"=> $field_element->getAttribute("name"),
					"type"=> $field_element->getAttribute("type"),
					"isarray"=> $field_element->getAttribute("isarray"));
			
			$all_fields[count($all_fields)] = $field_info;	
		}
		
		$inherited_elements = $table_element->childNodes;
		foreach($inherited_elements as $inherited_element)
		{
			if($inherited_element->tagName != "inherited")
			{
				continue;
			}
			$inherited_table = $inherited_element->nodeValue;
			$pos = strpos($inherited_table, ".");
			$inherited_table_owner_module = trim(substr($inherited_table, 0, $pos));
			$inherited_table_name = trim(substr($inherited_table, $pos+1));
			
			
			$inherited_module_xml = $project_home.trim($inherited_table_owner_module)."/module.xml";
			$inherited_doc = new DOMDocument();
			$inherited_doc->load($inherited_module_xml);
			
			
			$inherited_table_elements = $inherited_doc->documentElement->childNodes;
			foreach ($inherited_table_elements as $inherited_table_element)
			{	
				if($inherited_table_element->nodeType != XML_ELEMENT_NODE)
				{
					continue;
				}
				if($inherited_table_element->getAttribute("name") == $inherited_table_name)
				{
					$inherited_field_elements = $inherited_table_element->childNodes;
					/*$inherited_field_elements = 
						array_merge($inherited_field_elements, $field_elements);*/
					foreach($inherited_field_elements as $inherited_field_element)
					{		
						if($inherited_field_element->nodeType != XML_ELEMENT_NODE)
						{
							continue;
						}	
						if($inherited_field_element->tagName != "field")
						{
							continue;
						}
						$name = $inherited_field_element->getAttribute("name");
						if($direct_fields[$name] == 1)
						{
							continue;
						}
						/*$inherited_table_element-> removeChild($inherited_field_element);
						$table_element->appendChild($inherited_field_element); */
						$field_info = array(
								"name"=> $inherited_field_element->getAttribute("name"),
								"type"=> $inherited_field_element->getAttribute("type"),
								"isarray"=> $inherited_field_element->getAttribute("isarray"));
						
						$all_fields[count($all_fields)] = $field_info;
					}
					break;
				}
			}
		}
		
		
		for($i = 0; $i < count($all_fields); $i ++)
		{
			$field_info = $all_fields[$i];
			$field_type = $field_info["type"];
			if(substr($field_type, 0, 5) == "Table"	)
			{
				$table_name = substr($field_type, 6);
				$field_info["istable"] = 1;
				$field_info["table"] = $table_name;
				$all_fields[$i] = $field_info;
			}
		}
		return $all_fields;
	}
}

function build_conf_tree($node, $base_name)
{
	$childs = $node->childNodes;
	$i = 0;
	foreach($childs as $child)
	{
		$table = $child->getAttribute("table");
		$field_name = $child->getAttribute("name");
		if($table != NULL) //then it is a table..
		{
			$table_module = $child->getAttribute("table_module");
			$op = $child->getAttribute("op");
			if($op == NULL)
			{
				$op = "open"; //the default value..
			}
			$new_base_name = $base_name."__".$i;
			
			
			$component_html = "<div style='width:350px'>";
			$component_html .= "<div style='width:70%; float:left'>";
			$component_html .= $field_name." (".$table_module.":".$table.")";
			$component_html .= "</div>";
			$component_html .= "<div style='width:15%; float:left'>";
			$component_html .= "<img title='Open from Existing entries' src='img/open.gif'/>";
			$component_html .= 
				"<input type='radio' ";
			if($op == "open")
			{
				$component_html .= "checked=true ";
			}
			$component_html .= "onclick='change_conf(this)' op='open' name='${new_base_name}' id='${new_base_name}_open'/>";
			$component_html .= "</div>";
			$component_html .= "<div style='width:15%, float:right'>";
			$component_html .= "<img title='Create new entries' src='img/new.gif'/>";
			$component_html .= 
				"<input type='radio' ";
			if($op == "new")
			{
				$component_html .= "checked=true ";
			}
			$component_html .= "onclick='change_conf(this)' op='new' name='${new_base_name}' id='${new_base_name}_new'/>";
			$component_html .= "</div>";
			$component_html .= "</div>";

			
			echo 
			"var $new_base_name = new YAHOO.widget.HTMLNode(\"${component_html}\",
					${base_name}, true, true);
			";
			
			if($op == "new")
			{
				build_conf_tree($child, $new_base_name);
			}
			
		}
		$i ++;
	}
}

//now write code for select the container..
$crud_xml = NULL;
$crud_page_xml = NULL;
if(isset($current_module_name) && isset($current_table_name) && 
	$current_module_name != "" && $current_table_name != "" && $doc != NULL)
{
	$composite_params = $root_project_home."___".$current_module_name."___".$current_table_name;
	$page_xml = "./bin/".$conf_dir.$current_module_name."_".$current_table_name."_page.xml";
	$page_designer_url = "../../page_designer/index.php?page_xml=".$page_xml.
						"&project_home=".$root_project_home.
						"&plugin_comp=CRUD&plugin_param=".$composite_params.
						"&plugin_return=../plug_ins/CRUD/index.php";
	
	$crud_xml = $conf_dir.$current_module_name."_".$current_table_name.".xml";
	$crud_page_xml = $conf_dir.$current_module_name."_".$current_table_name."_page.xml";
}
else
{
	$page_designer_url = "#";
}
?>

<script language="javascript">
function init()
{
 var confTree = new YAHOO.widget.TreeView("confTree");
 var root = confTree.getRoot();
 
 var componentHTML = "<?php echo $current_module_name?>: <?php echo $current_table_name?>";

 var base = new YAHOO.widget.HTMLNode(componentHTML,
					root, true, true);
					
 <?php 
	if(isset($current_module_name) && isset($current_table_name) && 
		$current_module_name != "" && $current_table_name != "" && $doc != NULL)
	{
		$node = $doc->documentElement;
		build_conf_tree($node, "base");
		echo "confTree.draw();";
	}
 ?>
}

function change_conf(ctrl)
{
	var op_name = ctrl.getAttribute("name");
	var op_act = ctrl.getAttribute("op");
	//alert(document.forms[0].action);
	window.location.href= "index.php?op_name=" + op_name +
							"&op_act="+ op_act +
							"&moduleName=" + "<?php echo $current_module_name; ?>" +
							"&tableName=" + "<?php echo $current_table_name; ?>" +
							"&project_home=" + "<?php echo $root_project_home; ?>";
}
</script>

<?php
if(!isset($current_module_name) || $current_module_name == "")
{
	$current_module_name = "Select a module";
}
if(!isset($current_table_name) || $current_table_name == "")
{
	$current_table_name = "Select a table";
}

?>


<form method="get" action="index.php">
<table width="560" border="0" cellpadding="0" cellspacing="0">
  <!--DWLayoutTable-->
  <tr>
    <td width="51" height="73">&nbsp;</td>
    <td width="129">&nbsp;</td>
    <td width="60">&nbsp;</td>
    <td width="95">&nbsp;</td>
    <td width="160">&nbsp;</td>
    <td width="65">&nbsp;</td>
  </tr>
  <tr>
    <td height="38">&nbsp;</td>
    <td colspan="4" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
      <!--DWLayoutTable-->
      <tr>
        <td width="444" height="38" valign="top"><h2>CRUD SEMF Plugin </h2></td>
        </tr>
    </table></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="41">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="40"></td>
    <td valign="top">Starting Entity </td>
    <td colspan="2" valign="top">
      <select onchange="this.form.submit()" id="moduleName" name="moduleName"
	  			 value="<?php echo $current_module_name;?>">
	  	<?php
			$current_value_found = false;
			foreach($modules as $module)
			{
				$code = "<option onclick='this.form.submit()' value='".$module."' ";
				if($module == $current_module_name)
				{
					$current_value_found = true;
					$code .= "selected=1";
				}
				$code .= ">".$module."</option>";
				echo $code;
			}
			if(!$current_value_found)
			{
				echo "<option selected value=''>".$current_module_name."</option>";
			} 
		?>
      </select>	</td>
    <td valign="top">
		<select onchange="this.form.submit()" id="tableName" name="tableName"
				 value="<?php echo $current_table_name;?>">
	  	<?php
			$current_value_found = false;
			foreach($tables as $table)
			{
				$code = "<option onclick='this.form.submit()' value='".$table."'";
				if($table == $current_table_name)
				{
					$current_value_found = true;
					$code .= "selected=1";
				}
				$code .= ">".$table."</option>";
				echo $code;
			}
			if(!$current_value_found && count($tables) == 0)
			{
				echo "<option selected=1 value=''>".$current_table_name."</option>";
			}
		?>
		</select>    </td>
    <td></td>
  </tr>
  
  <tr>
    <td height="41">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="35">&nbsp;</td>
    <td valign="top">Targetted Container: </td>
    <td>&nbsp;</td>
    <td colspan="2" valign="top">
	<?php echo $container_id; ?>
	<img style="cursor:pointer" 
		onclick="window.location.href='<?php echo $page_designer_url;?>'" 
		align="baseline" src="img/search.gif" />
	</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td height="50">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
<input name="project_home" value="<?php echo $root_project_home; ?>" type="hidden" />
</form>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <!--DWLayoutTable-->
  <tr>
	<td width="106" height="19">&nbsp;</td>
    <td width="636" valign="top">
	<div id="confTree">	    </div></td>
  </tr>
</table>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <!--DWLayoutTable-->
  <tr>
	<td height="30">&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
	<td width="106" height="19">&nbsp;</td>
    <td width="636" valign="top">
	<a title="generate page" 
		href="generate.php?crud_xml=<?php echo $crud_xml; ?>&crud_page_xml=<?php echo $crud_page_xml; ?>&container=<?php echo $container_id ?>&project_home=<?php echo $root_project_home; ?>">Generate</a>
	</td>
  </tr>
</table>
<script language="javascript">
init();
</script>
</body>
</html>
